Sets

Data structure for storing sets of items.


In [1]:
s=set() #this is how you create a set

s.add(5) #this is how you add items to sets
s.add("hi")
s.add(5)
s.add("ho")
s.add("hi")

s1=set([1,2,3,4,5]) #and you can also create sets from lists or any other iterables
s2=set([4,5,6,7])

#sets allow basic set operations
print("s1",s1)
print("s2",s2)
print("s1&s2",s1&s2) #intersection
print("s1-s2",s1-s2) #difference
print("s1|s2",s1|s2) #union

print("s1 before union update",s1)
s1.update(s2)#union in-place
print("s1 after union update",s1)


s1 {1, 2, 3, 4, 5}
s2 {4, 5, 6, 7}
s1&s2 {4, 5}
s1-s2 {1, 2, 3}
s1|s2 {1, 2, 3, 4, 5, 6, 7}
s1 before union update {1, 2, 3, 4, 5}
s1 after union update {1, 2, 3, 4, 5, 6, 7}

Set.remove() causes an error in case the item is not there.


In [2]:
s1.remove(11)


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-2-959f649fdfce> in <module>
----> 1 s1.remove(11)

KeyError: 11

Exceptions and try/except

The try ... except block can be used to intercept these errors and recover


In [3]:
import traceback  #needed if we want to print the error

try:
    #Code to run
    s1.remove(11)
except KeyError: #react on key errors
    #Code to run at the moment when an error happens in between try and except
    print("Error. Happened. I'm inside except!")
    traceback.print_exc() #print the erorr (note - iPython notebook catches this and turns into the red block seemingly in the wrong place)
    #error processed now, program continues
    
print("woohoo made it to the end")


Error. Happened. I'm inside except!
woohoo made it to the end
Traceback (most recent call last):
  File "<ipython-input-3-ae4fca87159b>", line 5, in <module>
    s1.remove(11)
KeyError: 11

In [ ]: